package com.hakim.wfb.web.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpUtil {

    final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    static HttpClient httpclient = null;


    static {
        try {
            SSLContext sslcontext = SSLContexts.custom().useTLS()
                    .loadTrustMaterial(null, new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] chain, String authType)
                                throws CertificateException {
                            return true;
                        }
                    })
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", sslsf)
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            connManager.setMaxTotal(2000);
            httpclient = HttpClients.custom().setConnectionManager(connManager).build();
        } catch (Exception ex) {
            logger.error("httpClient 初始化失败", ex);
        }
    }

    public static Map<String,String> uploadFile(HttpServletRequest request, String url, String method, Map<String, String> requestParams, File file, String accessToken) throws IOException {

        HttpPost httppost = new HttpPost(url+"/upload");
        //解决中文乱码问题
        ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("file", file);
        Iterator iter = requestParams.entrySet().iterator();
        while(iter.hasNext()) {
            Map.Entry entry = (Map.Entry)iter.next();
            builder.addTextBody((String) entry.getKey(), String.valueOf(entry.getValue()), contentType);
        }
        HttpEntity reqEntity = builder.build();
        httppost.setHeader("RemoteAddr", request.getRemoteHost());
        httppost.setEntity(reqEntity);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(20000).build();
        httppost.setConfig(requestConfig);
        HttpResponse reusltResponse = httpclient.execute(httppost);
        Map map = getJsonData(reusltResponse);
        httppost.releaseConnection();
        return map;
    }

    /**
     * 根据repsonse获得返回值
     *
     * @param reusltResponse
     * @return
     * @throws IOException
     */
    private static Map<String,Object> getJsonData(HttpResponse reusltResponse)
             {
        Map<String,Object> resMap = new HashMap<>();
        int code = reusltResponse.getStatusLine().getStatusCode();
        String jsonString = "";
        if (200 != code) {
            resMap.put("retCode", -1);
            resMap.put("retMsg", "上传失败："+String.valueOf(code));
            resMap.put("url", "");
        } else {
            try {
                jsonString = EntityUtils.toString(reusltResponse.getEntity());
                JSONObject json = JSONObject.parseObject(jsonString);
                return json;
            } catch (Exception e) {
                logger.error("获得API接口数据出错,API返回的内容是:" + jsonString);
                resMap.put("retCode", -1);
                resMap.put("retMsg", "上传失败："+String.valueOf(code));
            }
        }

        return resMap;
    }
}
